//
//  LeslieAsyncImageDownloader.m
//  AsyncUIImageView
//
//  Created by Leslie.Fang on 14-8-11.
//  Copyright (c) 2014年 Enway. All rights reserved.
//

#import "AsyncVideoImageDownloader.h"

@implementation AsyncVideoImageDownloader

+(id)sharedImageLoader{
    static AsyncVideoImageDownloader *sharedImageLoader = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedImageLoader = [[self alloc] init];
    });
    
    return sharedImageLoader;
}

- (void)downloadImageWithURL:(NSURL *)url complete:(ImageDownloadedBlock)completeBlock{
    if (!url) {
        if (completeBlock) {
            NSLog(@"error :: url is nil ");
            completeBlock(nil,nil,url);
        }
        return;
    }
    
    VideoImageCache *imageCache = [VideoImageCache sharedCache];
    NSString *videoUrl = [url absoluteString];
    UIImage *image = [imageCache getImageFromMemoryForkey:videoUrl];
    // 先从内存中取
    if (image) {
        if (completeBlock) {
            NSLog(@"image exists in memory");
            completeBlock(image,nil,url);
        }
        
        return;
    }
    
    // 再从文件中取
    image = [imageCache getImageFromFileForKey:videoUrl];
    if (image) {
        if (completeBlock) {
            NSLog(@"image exists in file");
            completeBlock(image,nil,url);
        }
        
        // 重新加入到 NSCache 中
        [imageCache cacheImageToMemory:image forKey:videoUrl];
        
        return;
    }
    
    // 内存和文件中都没有再从网络下载
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSError * error;
        UIImage *image = [self thumbnailImageForVideo:url atTime:0];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (image) {
                // 先缓存图片到内存
                [imageCache cacheImageToMemory:image forKey:videoUrl];
                
                // 再缓存图片到文件系统
                NSString *imageType = @"jpg";
                
                [imageCache cacheImageToFile:image forKey:videoUrl ofType:imageType];
            }
            
            if (completeBlock) {
                completeBlock(image,error,url);
            }
        });
    });
}

- (UIImage*) thumbnailImageForVideo:(NSURL *)videoURL atTime:(NSTimeInterval)time {
    
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
    NSParameterAssert(asset);
    
    AVAssetImageGenerator *assetImageGenerator =[[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetImageGenerator.appliesPreferredTrackTransform = YES;
    //解决 时间不准确问题
    assetImageGenerator.requestedTimeToleranceBefore = kCMTimeZero;
    assetImageGenerator.requestedTimeToleranceAfter = kCMTimeZero;
    assetImageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
    
    // 获取视频总时长,单位秒
    Float64 durationSeconds = CMTimeGetSeconds([asset duration]);
    NSLog(@"durationSeconds = %f  ~!~!~!~",durationSeconds);
    
    CGImageRef thumbnailImageRef = NULL;
    CFTimeInterval thumbnailImageTime = time;
    NSError *error = nil;
    CMTime actualTime;
    
    thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60)actualTime:&actualTime error:&error];
    
    if(!thumbnailImageRef){
        NSLog(@"thumbnailImageGenerationError = %@",error);
    }
    
    CMTimeShow(actualTime);
    
    NSString *actualTimeString = (NSString *)CFBridgingRelease(CMTimeCopyDescription(NULL, actualTime));
    
    NSLog(@" actual %@", actualTimeString);
    
    UIImage*thumbnailImage = thumbnailImageRef ? [[UIImage alloc]initWithCGImage:thumbnailImageRef] : nil;
    NSLog(@"thumbnailImage =  %@",thumbnailImage);
    
    return thumbnailImage;
}

@end
